package article2.builder;

/**
 * 第三种实现方法：Builder模式的一种形式。不直接生成想要的对象。然后客户端在builder对象上调用类似于setter的方法，
 * 来设置每个相关的可选参数。最后，客户端调用无参的build方法来生成不可变的对象。这个builder是它构建的类的静态成员类。
 *
 *
 * @author cctv
 */
public class NutritionFactsByBuilder {
    /**
     * (ml)                required
     */
    private final int servingSize;

    /**
     * (per container)    required
     */
    private final int servings;

    /**
     * optional
     */
    private final int calories;

    /**
     * (g)                optional
     */
    private final int fat;

    /**
     * (mg)                optional
     */
    private final int sodium;

    /**
     * (g)                optional
     */
    private final int carbohydrate;


    public static class Builder {
        //Required parameters

        private final int servingSize;
        private final int servings;

        //optional parameters - initialized to default values

        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbohydrate = 0;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int val) {
            calories = val;
            return this;
        }

        public Builder fat(int val) {
            fat = val;
            return this;
        }

        public Builder carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }

        public Builder sodium(int val) {
            sodium = val;
            return this;
        }

        public NutritionFactsByBuilder build() {
            return new NutritionFactsByBuilder(this);
        }
    }

    private NutritionFactsByBuilder(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;

    }
}
